package com.shawn.baseappbygroovydsl.utils

import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.widget.Toast
import com.shawn.baseappbygroovydsl.base.AppBase
import com.shawn.baseappbygroovydsl.ui.extension.ExtensionLog.log
import java.util.Locale


object UtilStoreApp {

    // 不同应用商店的包名和跳转协议
    const val GOOGLE_PLAY: String = "com.android.vending"
    const val HUAWEI_APPGALLERY: String = "com.huawei.appmarket"
    const val XIAOMI_APPSTORE: String = "com.xiaomi.market"
    const val OPPO_APPSTORE: String = "com.oppo.market"
    const val VIVO_APPSTORE: String = "com.bbk.appstore"
    const val HONOR_APPSTORE: String = "com.hihonor.appmarket"
    const val SAMSUNG_APPSTORE: String = "com.sec.android.app.samsungapps"
    const val TENCENT_APPSTORE: String = "com.tencent.android.qqdownloader"
    const val BAIDU_APPSTORE: String = "com.baidu.appsearch"
    const val QH360_APPSTORE: String = "com.qihoo.appstore"

    const val JD : String = "com.jingdong.app.mall"
    const val TAOBAO : String = "com.taobao.taobao"

    fun isPkgInstall(adPkgName: String): Boolean {
        runCatching {
            val applicationInfo = AppBase.instance.packageManager.getApplicationInfo(adPkgName, 0);
            return adPkgName == applicationInfo.packageName
        }
        return false
    }


    /**
     * 跳转应用商店
     * */
    fun redirectToStore(targetPackageName: String) {
        val stores = detectAvailableStores()
        if (stores.isEmpty()) {
            jumpWeb(targetPackageName)
        } else {
            var success = false
            for (store in stores) {
                try {
                    jumpToStore(store, targetPackageName)
                    success = true
                    break
                } catch (e: Exception) {
                    continue
                }
            }
            if (!success) {
                jumpWeb(targetPackageName)
            }
        }
    }

    private fun jumpToStore(store: StoreInfo, targetPackageName: String) {
        val intent = Intent(Intent.ACTION_VIEW)
        intent.setData(Uri.parse(store.scheme + targetPackageName))
        intent.setPackage(store.packageName)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        AppBase.instance.startActivity(intent)
    }

    private fun jumpWeb(targetPackageName: String) {
        val context = AppBase.instance
        try {
            val intent = Intent(Intent.ACTION_VIEW)
            intent.setData(Uri.parse(convertToBaiduSearch(targetPackageName)))
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
        } catch (ex: ActivityNotFoundException) {
            Toast.makeText(context, "无法打开应用商店", Toast.LENGTH_SHORT).show()
        }
    }

    private fun convertToBaiduSearch(packageName: String): String {
        return "https://www.baidu.com/s?wd=$packageName+app"
    }

    private fun detectAvailableStores(): List<StoreInfo> {
        val brandName: String = Build.BRAND.lowercase(Locale.ROOT)
        val stores: MutableList<StoreInfo> = ArrayList()

        if (isPkgInstall(HUAWEI_APPGALLERY)) {
            stores.add(StoreInfo("华为应用市场", HUAWEI_APPGALLERY, "appmarket://details?id="))
        }

        if (isPkgInstall(HONOR_APPSTORE)) {
            stores.add(StoreInfo("荣耀应用市场", HONOR_APPSTORE, "appmarket://details?id="))
        }

        if (isPkgInstall(XIAOMI_APPSTORE)) {
//            stores.add(StoreInfo("小米应用商店", XIAOMI_APPSTORE, "mimarket://details?id="))
            stores.add(StoreInfo("小米应用商店", XIAOMI_APPSTORE, "market://search?q="))
        }

        val marketPkg = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            "com.heytap.market" //// Q （10）之后的软件商店包名
        } else {
            "com.oppo.market" //Q （10）之前的软件商店包名
        }
        if (isPkgInstall(marketPkg) || brandName == "oppo") {
            stores.add(
                StoreInfo(
                    "OPPO应用商店",
                    marketPkg,
                    "oppomarket://details?packagename="
                )
            )
        }

        if (isPkgInstall(VIVO_APPSTORE) || brandName == "vivo") {
            stores.add(StoreInfo("VIVO应用商店", VIVO_APPSTORE, "vivomarket://details?id="))
        }

        if (isPkgInstall(SAMSUNG_APPSTORE)) {
            stores.add(StoreInfo("三星应用商店", SAMSUNG_APPSTORE, "samsungapps://ProductDetail/"))
        }

        if (isPkgInstall(TENCENT_APPSTORE)) {
            stores.add(StoreInfo("腾讯应用宝", TENCENT_APPSTORE, "mmarket://details?id="))
        }

        if (isPkgInstall(BAIDU_APPSTORE)) {
            stores.add(StoreInfo("百度手机助手", BAIDU_APPSTORE, "bdapp://detail?pid="))
        }

        if (isPkgInstall(QH360_APPSTORE)) {
            stores.add(StoreInfo("360手机助手", QH360_APPSTORE, "qihoo://detail?packagename="))
        }

        if (isPkgInstall(GOOGLE_PLAY)) {
            stores.add(StoreInfo("Google Play", GOOGLE_PLAY, "market://details?id="))
        }
        return stores
    }

    data class StoreInfo(val name: String, val packageName: String, val scheme: String)


    fun openAppByPackageName(packageName: String) {
        try {
            val mContext = AppBase.instance
            if (isPkgInstall(packageName)) {
                val launchIntentForPackage =
                    mContext.packageManager.getLaunchIntentForPackage(packageName)
                if (launchIntentForPackage != null) {
                    launchIntentForPackage.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    mContext.startActivity(launchIntentForPackage)
                }
            } else {
                redirectToStore(packageName)
            }
        } catch (e: Exception) {
            e.message?.log("open app:")
        }
    }

    fun openAppByPackageName(packageName: String, finish: (() -> Unit)) {
        try {
            val mContext = AppBase.instance
            if (isPkgInstall(packageName)) {
                val launchIntentForPackage =
                    mContext.packageManager.getLaunchIntentForPackage(packageName)
                if (launchIntentForPackage != null) {
                    launchIntentForPackage.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    mContext.startActivity(launchIntentForPackage)
                }
            } else {
                finish.invoke()
            }
        } catch (e: Exception) {
            e.message?.log("open app:")
        }
    }

    fun getTargetStr(target: String): String {
        return if (target.contains("taobao")) {
            "淘宝"
        } else if (target.contains("jd") || target.contains("jingdong")) {
            "京东"
        } else if (target.contains("ele")) {
            "饿了么"
        } else if (target.contains("meituan")) {
            "美团"
        } else if (target.contains("pinduoduo")) {
            "拼多多"
        } else if (target.contains("com.ss.android.ugc.aweme")) {
            "抖音"
        } else {
            "平台"
        }
    }
}